package com.ishanshan.gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator;
import org.springframework.cloud.netflix.zuul.filters.discovery.ServiceRouteMapper;

/**
 * Created by WANGHJ on 2019-01-18.
 */
@Slf4j
public class CustomRouteLocator extends DiscoveryClientRouteLocator {

    private boolean hasProjectName = true;

    public CustomRouteLocator(String servletPath, DiscoveryClient discovery, ZuulProperties properties) {
        super(servletPath, discovery, properties);
    }

    public CustomRouteLocator(String servletPath, DiscoveryClient discovery, ZuulProperties properties, ServiceInstance localServiceInstance) {
        super(servletPath, discovery, properties, localServiceInstance);
    }

    public CustomRouteLocator(String servletPath, DiscoveryClient discovery, ZuulProperties properties, ServiceRouteMapper serviceRouteMapper) {
        super(servletPath, discovery, properties, serviceRouteMapper);
    }

    public CustomRouteLocator(String servletPath, DiscoveryClient discovery, ZuulProperties properties, ServiceRouteMapper serviceRouteMapper, ServiceInstance localServiceInstance) {
        super(servletPath, discovery, properties, serviceRouteMapper, localServiceInstance);
    }

    public boolean isHasProjectName() {
        return hasProjectName;
    }

    public void setHasProjectName(boolean hasProjectName) {
        this.hasProjectName = hasProjectName;
    }


    @Override
    public Route getMatchingRoute(final String path) {
        String adjustedPath = path;
        if(hasProjectName){
            if(adjustedPath.startsWith("/api")){
                adjustedPath = adjustedPath.replaceFirst("/api/","");
            }
            int i =  adjustedPath.indexOf("/");
            adjustedPath = "/api" + adjustedPath.substring(i);
        }
        return super.getMatchingRoute(adjustedPath);

    }
}
